/**
 * 
 */
package edu.pw.treegrid.server.classmodel;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import edu.pw.treegrid.server.query.Node;
import edu.pw.treegrid.server.query.TableNode;
import edu.pw.treegrid.server.reportmodel.ReportColumn;
import edu.pw.treegrid.server.service.XMLMarshaller;

/** 
 * @author Piotrek
 */
public class ReferenceAttribute extends DomainAttribute {

	public static final String REF_ATTRIBUTE = "ref";
	public static final String REFERENCE_CLASS_ELEMENT = "referenceClass";
	public static final String JOIN_COLUMN_NAME_ELEMENT = "joinColumnName";
	private String joinColumnName;
	private String referenceClassId;
	
	public String getJoinColumnName() {
		return joinColumnName;
	}

	public void setJoinColumnName(String joinColumnName) {
		this.joinColumnName = joinColumnName;
	}

	private DomainClass referenceClass;

	public DomainClass getReferenceClass() {
		return referenceClass;
	}

	public void setReferenceClass(DomainClass referenceClass) {
		this.referenceClass = referenceClass;
	}

	public Node buildQueryNode(ReportColumn reportColumn) {
		TableNode tn = new TableNode();
		tn.setTableName(getReferenceClass().getTableName());
		tn.setNumber(1);
		tn.setForeignKeyName(joinColumnName);
		tn.setPrimaryKeyName(getReferenceClass().getPrimaryAttribute()
				.getExpression());
		tn.setReportColumn(reportColumn);
		return tn;
	}

	public SimpleAttribute getSimpleAttribute() {
		return null;
	}

	@Override
	protected void serializeToXML(Document document, Element attributeElement) {
		Element joinColumnNameElement = document.createElement(JOIN_COLUMN_NAME_ELEMENT);
		joinColumnNameElement.setTextContent(this.joinColumnName);
		attributeElement.appendChild(joinColumnNameElement);
		
		Element referenceClassElement = document.createElement(REFERENCE_CLASS_ELEMENT);
		referenceClassElement.setAttribute(REF_ATTRIBUTE, referenceClass.getId());
		attributeElement.appendChild(referenceClassElement);
	}
	
	@Override
	protected void deserializeFromXML(Element ae) {
		super.deserializeFromXML(ae);
		
		this.joinColumnName = getElementsText(ae, JOIN_COLUMN_NAME_ELEMENT);
		this.referenceClassId = getAttributeText(getFirstElement(ae, REFERENCE_CLASS_ELEMENT), REF_ATTRIBUTE);
	}
	
	@Override
	public void setReferences(XMLMarshaller xmlMarshaller) {
		super.setReferences(xmlMarshaller);
		
		this.referenceClass = xmlMarshaller.getClassById(this.referenceClassId);
	}

}